<?php
// Load FLATDATA
require_once $mytrustdirpath."/class/flatdata.class.php";
$flatdata = new Flatdata($mydirname);
// ALL Fields
$allfields = $fields->getAllFields();


/* ------------------------------------------------------------------ */
//EXPORT
$err_flag = FALSE;
if (isset($_POST['export_submit'])) {
	if (! $xoopsGTicket->check(TRUE, 'flatdata_admin_export')) {
		redirect_header(XOOPS_URL .'/', 3, $xoopsGTicket->getErrors());
	}

	$fileName = $mydirname . '_export_' . date('Ymd_Hi') . '.csv';
	$filePath = XOOPS_ROOT_PATH . '/uploads/' . $fileName;

	if (isset($_POST['type']) && $_POST['type'] == 2) {
		$fidarr = $fields->getFidArray();
		$flatdata->setOrder('A');
		$data = $flatdata->getDatas($fidarr, 0, 0, TRUE);

		// LINE 1 fields name
		$csvData  = '"did",';
		foreach ($allfields as $f) {
			$csvData .= formatQuote($f['fname']);
		}
		$csvData .= '"uid","regidate","embed","cat_id","hits"';
		$csvData .= "\n";
		// DATA part
		foreach ($data as $d) {
			$csvData .= formatQuote($d['did']);
			foreach ($fidarr as $fa) {
				$d['data'][$fa] = isset($d['data'][$fa]) ? $d['data'][$fa]: '';
				$csvData .= formatQuote($d['data'][$fa]);
			}
			$csvData .= formatQuote($d['uid']);
			$csvData .= formatQuote(date('Y-n-j H:i', $d['regidate']));
			$csvData .= formatQuote($d['embed']);
			$csvData .= formatQuote($d['cat_id']);
			$csvData .= formatQuote($d['hits']);
			$csvData = rtrim($csvData, ',');
			$csvData .= "\n";
		}

		$err_flag = saveCSV($filePath, $csvData);

	} else {

		// OUTFILEDUMPFILE
		$sql = 'SELECT `did`, `data`, `uid`, `regidate`, `embed`, `cat_id`, `hits` FROM `'. $xoopsDB->prefix($mydirname.'_data') .'` INTO OUTFILE "'. $filePath .'" CHARACTER SET shift-jis FIELDS TERMINATED BY "," OPTIONALLY ENCLOSED BY "\""';
		$xoopsDB->query($sql);

		if (!file_exists($filePath)) {
			$sql = 'SELECT `did`, `data`, `uid`, `regidate`, `embed`, `cat_id`, `hits` FROM `'. $xoopsDB->prefix($mydirname.'_data') .'` ORDER BY did ASC';
			$result = $xoopsDB->query($sql);
			$csvData = '';
			while ($row = $xoopsDB->fetchArray($result)) {
				$csvData .= formatQuote($row['did']);
				$csvData .= formatQuote($row['data']);
				$csvData .= formatQuote($row['uid']);
				$csvData .= formatQuote($row['regidate']);
				$csvData .= formatQuote($row['embed']);
				$csvData .= formatQuote($row['cat_id']);
				$csvData .= formatQuote($row['hits']);
				$csvData = rtrim($csvData, ',');
				$csvData .= "\n";
			}

			$err_flag = saveCSV($filePath, $csvData);
		}
	}

	// Download
	if (file_exists($filePath) && $err_flag === FALSE) {
		header('Content-Type:application/octet-stream; charset=Shift-JIS');
		header('Content-Disposition:attachment; filename=' . $fileName);
		header('Content-Transfer-Encoding: binary'); 
		header('Expires: 0');
		if (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
			header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
			header('Pragma: public');
		} else {
			header('Pragma: no-cache');
		}
		header('Content-Length: ' . filesize($filePath));
		readfile($filePath);

		@unlink($filePath);
		exit;
	} else {
		$err_flag = TRUE;
	}

}
/* ------------------------------------------------------------------ */





/* ------------------------------------------------------------------ */
xoops_cp_header() ;
include dirname(__FILE__).'/mymenu.php' ;

if ($err_flag) {
	echo '<div style="color:#f00;margin:20px 0;">EXPORT ERROR</div>';
} else {

	if (count($allfields) > 0 || $flatdata->getCount() > 0) {
		echo '<h3>'. htmlspecialchars($xoopsModule->getVar('name'), ENT_QUOTES, _CHARSET) .' - '. constant($constprefMI .'_ADMENU4') .'</h3>';
		echo sprintf(_MD_A_FLATDATA_EXPORT_MSG0, $xoopsDB->prefix($mydirname . '_data')), '<br /><br />';
		echo _MD_A_FLATDATA_EXPORT_MSG1, '<br />';
		$fields = '';
		foreach ($allfields as $f) {
			$fields .= htmlspecialchars($f['fname'], ENT_QUOTES, _CHARSET) . ', ';
		}
		echo sprintf(_MD_A_FLATDATA_EXPORT_MSG2, $fields);
		echo '<form action="" method="post" style="margin:20px 0;">';
		echo '<input type="submit" name="export_submit" value="'. _MD_A_FLATDATA_EXPORT_SUBMIT .'" /><br /><br />';
		echo '<input type="radio" name="type" value="1" checked="CHECKED" />' . _MD_A_FLATDATA_EXPORT_TYPE_DB, '&nbsp;';
		echo '<input type="radio" name="type" value="2" />' . _MD_A_FLATDATA_EXPORT_TYPE_FIELD;
		echo $xoopsGTicket->getTicketHtml(__LINE__, 1800, 'flatdata_admin_export');
		echo '</form>';
	} else {
		echo _MD_A_FLATDATA_EXPORT_ERR_MSG;
	}

}
xoops_cp_footer();
/* ------------------------------------------------------------------ */


// TODO FUNCTIONS
function formatQuote($data)
{
	$data = empty($data) ? '': $data;
	return '"' . str_replace('"', '\"', $data) . '",';
}
function saveCSV($filePath, $csvData)
{
	$err_flag = TRUE;

	if (empty($csvData)) {
		return $err_flag;
	}
	$csvData = mb_convert_encoding($csvData, 'shift-jis', 'auto');

	$fp = fopen($filePath, 'wb');
	if (!is_resource($fp)) {
		return $err_flag;
	}
	flock($fp, LOCK_EX);
	fwrite($fp, $csvData);
	fclose($fp);
	$err_flag = FALSE;
	return $err_flag;
}